<?php
/*
 * @Descripttion: 
 * @version: 1.0
 * @Author: Sam
 * @Date: 2022-04-21 15:27:09
 * @LastEditors: Sam
 * @LastEditTime: 2023-01-10 11:11:32
 */
namespace app\api\controller;
use think\facade\Db;
use app\admin\model\{User as UserModel};

/**
 * 消息推送服务  小程序后台先要配置好
 * @author Sam
 * @date 2023-01-10
 */
class Push {

    const TOKEN = 'XXXXXXXXXX';  //小程序后台自定义token
    public function index(){
      
        if(isset($_GET["echostr"])){
            $check = $this->checkSignature();
            if($check){
                echo $_GET["echostr"];
                die;
            }
        }else{
            $this->check_image();
        }
    }

    /**
     * 图片检测
     * @return void
     * @author Sam
     * @date 2023-01-09
     */
    private function check_image(){
        $param = request()->post();
        if(isset($param['Event']) && $param['Event'] == 'wxa_media_check'){
            if($param['result']['label'] == 100){
                $trace =  Db::name('img_trace')->where('trace_id',$param['trace_id'])->find();
                if($trace && $trace['status'] == 0){
                    Db::name('img_trace')->where('trace_id',$param['trace_id'])->update([
                        'status' => 1,
                        'suggest' => $param['result']['suggest'],
                        'label'   => $param['result']['label'],
                        'create_time' => date('Y-m-d H:i:s')
                    ]);
                    ///具体逻辑   判断原数据库 有多少图片 判断图片是否全部通过 都通过 修改状态变成已审核或已显示
                }
                
            }
        }
        echo 'success';
        die;
    }
    /**
     * 初次验证
     * @return void
     * @author Sam
     * @date 2023-01-09
     */
    private function checkSignature()
        {
            $signature = $_GET["signature"];
            $timestamp = $_GET["timestamp"];
            $nonce = $_GET["nonce"];

            $token = self::TOKEN;
            $tmpArr = array($token, $timestamp, $nonce);
            sort($tmpArr, SORT_STRING);
            $tmpStr = implode( $tmpArr );
            $tmpStr = sha1( $tmpStr );

            if ($tmpStr == $signature ) {
                return true;
            } else {
                return false;
            }
        }
}

